using System;
using System.Collections.Generic;
using System.Configuration;


namespace ApiScanner.Core
{
	public abstract class DynamicConfigurationElementCollection<T>: ConfigurationElementCollection<T, Type>
		where T:SerializableConfigurationElement, new()
	{
	
		protected static void RegisterType<TItem>(string id)
			where TItem: T
		{
			ConfigurationKnownTypes.RegisterConfigurationElementType(id, typeof(TItem));
		}

		protected DynamicConfigurationElementCollection()
		{
		}

		protected DynamicConfigurationElementCollection(IEnumerable<T> items)
		{
			AddRange(items);
		}

		protected override object GetElementKey(T element)
		{
			return element.GetType();
		}

		protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader)
		{
			SerializableConfigurationElement instance;
			if (ConfigurationKnownTypes.TryGetType(elementName, out instance))
			{
				instance.Deserialize(reader);

				Add((T) instance);
				return true;
			}
			return true;
		}
		
		protected override void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
		{
			var items = (IEnumerable<T>)sourceElement;

			foreach (T schedule in items)
			{
				BaseAdd(schedule, true);
			}
		}
	}
}